package com.wmc.sqltransformweb.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @escription
 * @auther: wangmingchang
 * @date: 2019/1/23 13:44
 */
@Log4j2
public class FileUtil {
    private static List<String> canonicalPaths = new ArrayList<>();

    private static final String CHAR_UTF = "UTF-8";
    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(String jsonString, String filePath,String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + fileName + ".json";
        log.info("保存json的url:{}", filePath);
        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            if (jsonString.indexOf("'") != -1) {
                //将单引号转义一下，因为JSON串中的字符串类型可以单引号引起来的
                jsonString = jsonString.replaceAll("'", "\\'");
            }
            if (jsonString.indexOf("\"") != -1) {
                //将双引号转义一下，因为JSON串中的字符串类型可以单引号引起来的
                jsonString = jsonString.replaceAll("\"", "\\\"");
            }

            if (jsonString.indexOf("\r\n") != -1) {
                //将回车换行转换一下，因为JSON串中字符串不能出现显式的回车换行
                jsonString = jsonString.replaceAll("\r\n", "\\u000d\\u000a");
            }
            if (jsonString.indexOf("\n") != -1) {
                //将换行转换一下，因为JSON串中字符串不能出现显式的换行
                jsonString = jsonString.replaceAll("\n", "\\u000a");
            }

            // 格式化json字符串
            //jsonString = JsonFormatTool.formatJson(jsonString);

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), CHAR_UTF);
            StringBuffer context = new StringBuffer(jsonString);
            context.append(System.getProperty("line.separator"));
            write.write(context.toString());
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        // 返回是否成功的标记
        return flag;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            InputStream inStream = null; //读入原文件
            FileOutputStream fileOutputStream = null;
            try {
                if (oldfile.exists()) { //文件存在时
                    inStream = new FileInputStream(oldPath); //读入原文件
                    fileOutputStream = new FileOutputStream(newPath);

                    byte[] buffer = new byte[1024];
                    int length;
                    while ((byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread; //字节数 文件大小
                        fileOutputStream.write(buffer, 0, byteread);
                    }
                    inStream.close();
                }
            } catch (Exception e) {
                log.error("复制单个文件操作出错", e);
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            log.error("复制整个文件夹内容操作出错", e);
        }

    }

    /**
     * 判断文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean isExistFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * 根据路径扫描包下的文件名相同的文件
     *
     * @param path     需要扫描的路径
     * @param fileName 需要获取的文件名
     * @param suffix   文件后缀
     * @return
     */
    public static String scanFile(String path, String fileName, String suffix) {
        String canonicalPath = "";
        canonicalPaths.clear();
        scanFileList(path, fileName, suffix, canonicalPaths);
        if (null != canonicalPaths && canonicalPaths.size() > 0) {
            canonicalPath = canonicalPaths.get(0);
        }
        return canonicalPath;
    }

    private static void scanFileList(String path, String fileName, String suffix, List<String> canonicalPaths) {

        File file = new File(path);
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    //这一段是测试在console里面打印输出所有扫描到的文件，仅作调试使用。
                    try {
                        log.info("查找中:" + f.getCanonicalPath());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    String name = f.getName();
                    if (StringUtils.isNotBlank(suffix)) {
                        String newfileName = fileName + "." + suffix;
                        if (name.equals(newfileName)) {
                            try {
                                canonicalPaths.add(f.getCanonicalPath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        if (f.getName().indexOf(fileName) >= 0) {
                            try {
                                canonicalPaths.add(f.getCanonicalPath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else if (f.isDirectory()) {
                    scanFileList(f.getPath(), fileName, suffix, canonicalPaths);
                }
            }
        }

    }

    /**
     * 以字节为单位读取文件,常用语读取二进制文件,如图片,声音,影响等文件.
     */
    public static void readFileByBytes1(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取内容,一次读一个字节:");
            //一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.println(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            System.out.println("readFileByBytes1异常:IOException.....");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("readFileByBytes1异常:Exception.....");
            e.printStackTrace();
        }
    }
    /**
     * 以字节为单位读取文件,常用语读取二进制文件,如图片,声音,影响等文件.
     */
//    public static void readFileByBytes2(String fileName){
//        File file=new File(fileName);
//        InputStream in=null;
//        try {
//            System.out.println("以字节为单位读取内容,一次读多个字节");
//            //一次读多个字节
//            byte[] tempbytes=new byte[100];
//            int byteread=0;
//            in=new FileInputStream(fileName);
//            ReadFormFile.showAvailableBytes(in);
//            //读入多个字节到字节数组中,byteread为一次读入的字节数
//            while((byteread=in.read(tempbytes))!=-1){
//                System.out.write(tempbytes,0,byteread);
//            }
//        } catch (Exception e) {
//            System.out.println("readFileByBytes2异常:Exception....");
//        }finally{
//            if(in !=null){
//                try {
//                    in.close();
//                } catch (Exception e2) {
//                    // TODO: handle exception
//                }
//            }
//        }
//    }

    /**
     * 以字符为单位读取文件,长用于读取文本,数字类型的文件,一次读取一个字节
     */
    public static void readFileByChars1(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位,一次读取一个字节");
            //一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                //对于windows下，\r\n这两个字符在一起时，表示一个换行。
                // 但如果这两个字符分开显示时，会换两次行。
                // 因此，屏蔽掉\r，或者屏蔽\n。否则，将会多出很多空行。
                if ((char) tempchar != '\r') {
                    System.out.println((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 以字符为单位读取文件,长用于读取文本,数字类型的文件,一次读多个字节
     */
    public static void readFileByChars2(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容，一次读多个字节：");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中，charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读取一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            String result = "";
            //一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                //显示行号
                System.out.println("line" + line + ":" + tempString);
                //System.out.println(tempString);
                //result+=tempString;
                line++;
            }
            //System.out.println(result);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e2) {
                    System.out.println("readFileByLines异常.....");
                }
            }
        }
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容：");
            // 打开一个随机访问文件流，按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节，如果文件内容不足10个字节，则读剩下的字节。
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 显示输入流中还剩的字节数
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            System.out.println("showAvailableBytes异常:IOException.....");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("showAvailableBytes异常:Exception.....");
            e.printStackTrace();
        }
    }

    /**
     * A方法追加文件:使用RandowAccessFile
     */
    public static void appendMethodA(String fileName, String content) {
        try {
            //打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            //文件长度,字节数
            long fileLength = randomFile.length();
            //将写文件指针移到文件尾
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            System.out.println("appendMethodA异常....");
        }
    }

    /**
     * B方法追加文件:使用FileWriter
     */
    public static void appendMethodB(String fileName, String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示追加形式写入
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            System.out.println("appendMethodB异常...");
        }
    }

    /**
     * @param filename 目标文件
     * @param charset  目标文件的编码格式
     */
    public static void read(String filename, String charset) {
        RandomAccessFile rf = null;
        try {
            // 内存流, 作为临时流
            CharArrayWriter  tempStream = new CharArrayWriter();
            rf = new RandomAccessFile(filename, "rwd");
            long len = rf.length();
            long start = rf.getFilePointer();
            long nextend = start + len - 1;
            String line;
            rf.seek(nextend);
            int c = -1;
            while (nextend > start) {
                c = rf.read();
                if (c == '\n' || c == '\r') {
                    line = rf.readLine();
                    if (line != null) {
                        //替换]为空
                        if(line.trim().equals("]")){
                            line.replace("\\]","");
                            rf.write(line.getBytes());
                            tempStream.write("");
                            break;
                        }
                        System.out.println(new String(line
                                .getBytes(CHAR_UTF), charset));
                    } else {
                        System.out.println(line);
                    }
                    nextend--;
                }
                nextend--;
                rf.seek(nextend);
                if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                // System.out.println(rf.readLine());
                    System.out.println(new String(rf.readLine().getBytes(
                            CHAR_UTF), charset));
                }
            }
            //File file = new File(filename);
            // 将内存中的流 写入 文件
            FileWriter out = new FileWriter(rf.getFD());
            tempStream.writeTo(out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rf != null)
                    rf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 在json的"]"之前追加内容
     * @param fileName 要修改的文件名
     * @param jsonString 添加的内容
     */
    public static Boolean addJosnString(String fileName, String jsonString, String id){
        boolean flag = false;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(fileName, "rw");
            StringBuffer sb = new StringBuffer(System.getProperty("line.separator")).append(jsonString).append(System.getProperty("line.separator"));
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            while ((line = raf.readLine()) != null) {
                String currentLine = new String(line.getBytes("ISO-8859-1"), CHAR_UTF);
                log.info("currentLine:{}",currentLine);
                final long ponit = raf.getFilePointer();
                if(currentLine.contains(CURRENT_USED_FLAG) && !currentLine.contains(id)){
                    String newString = currentLine.replace(CURRENT_USED_FLAG, CURRENT_UNUSED_FLAG);
                    raf.seek(lastPoint);
                    raf.write(newString.getBytes());
                    break;
                }
                lastPoint = ponit;
            }
            // 文件长度，字节数
            long fileLength = raf.length();
            // 将写文件指针移到文件尾。
            raf.seek(fileLength);
            raf.write(sb.toString().getBytes());


            flag = true;
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
    private static final String CURRENT_USED_FLAG = "\"useFlag\":true";
    private static final String CURRENT_UNUSED_FLAG = "\"useFlag\":false";

    public static String getCurrnetJsonData(String fileName){
        if(!isExistFile(fileName)){
            return null;
        }
        try {
            LineIterator iterator = FileUtils.lineIterator(new File(fileName), CHAR_UTF);
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                if(line.contains(CURRENT_USED_FLAG)){
                    String jsondString = null;
                    if(line.startsWith(",")){
                        jsondString = line.replaceFirst(",", "");
                    }else {
                        jsondString = line;
                    }
                    return jsondString;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean updateDataFalseById(String fileName, String id){
        if(!isExistFile(fileName)){
            return false;
        }
        boolean flag = false;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(fileName, "rw");
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            boolean lastIsBlank = false;
            while ((line = raf.readLine()) != null) {
                String currentLine = new String(line.getBytes("ISO-8859-1"), CHAR_UTF);
                boolean currentIsBlank = false;
                if(StringUtils.isBlank(currentLine)){
                    currentIsBlank = true;
                }
                final long ponit = raf.getFilePointer();
                log.info("ponit:{},currentLine:{}, isBlank:{}",ponit, currentLine,currentIsBlank);
                if(currentLine.contains(CURRENT_USED_FLAG) && !currentLine.contains(id)){
                    log.info("updateDataFalseById-lastPoint:{}",lastPoint);
                    String newString = currentLine.replace(CURRENT_USED_FLAG, CURRENT_UNUSED_FLAG);
                    //更改当前使用的配置为false
                    long seekPoint = lastPoint;
                    if(lastIsBlank || seekPoint == 0){
                        newString += System.getProperty("line.separator");
                    }else {
                        newString = System.getProperty("line.separator") + newString + System.getProperty("line.separator");
                    }
                    log.info("updateDataFalseById-seekPoint1:{}", seekPoint);
                    raf.seek(seekPoint);
                    raf.write(newString.getBytes());
                    log.info("newString:{}",newString);
                }
                lastPoint = ponit;
                lastIsBlank = currentIsBlank;
            }

            flag = true;
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    private static void insert(String fileName, long pos, String content) throws IOException {
        //创建临时空文件
        File tempFile = File.createTempFile("temp", null);
        //在虚拟机终止时，请求删除此抽象路径名表示的文件或目录
        tempFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempFile);

        RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
        raf.seek(pos);
        byte[] buffer = new byte[4];
        int num = 0;
        while (-1 != (num = raf.read(buffer))) {
            fos.write(buffer, 0, num);
        }
        raf.seek(pos);
        raf.write(content.getBytes());
        FileInputStream fis = new FileInputStream(tempFile);
        while (-1 != (num = fis.read(buffer))) {
            raf.write(buffer, 0, num);
        }
    }



    public static boolean updateDataTrueById(String fileName, String id){
        if(!isExistFile(fileName)){
            return false;
        }
        boolean flag = false;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(fileName, "rw");
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            raf = new RandomAccessFile(fileName, "rw");
            boolean lastIsBlank = false;
            while ((line = raf.readLine()) != null) {
                String currentLine = new String(line.getBytes("ISO-8859-1"), CHAR_UTF);
                boolean currentIsBlank = false;
                if(StringUtils.isBlank(currentLine)){
                    currentIsBlank = true;
                }
                final long ponit = raf.getFilePointer();
                log.info("ponit:{},isBlank:{},currentLine2:{}",ponit,lastIsBlank, currentLine);
                if(currentLine.contains(id)){
                    //更新当前id为使用配置
                    long seekPoint = lastPoint;
                    log.info("更换前：{}",currentLine);
                    String str = currentLine.replace(CURRENT_UNUSED_FLAG, CURRENT_USED_FLAG);
                    if(lastIsBlank || seekPoint == 0){
                        str += System.getProperty("line.separator");
                    }else {
                        str = System.getProperty("line.separator") + str + System.getProperty("line.separator");
                    }
                    log.info("seekPoint2:{}", seekPoint);
                    raf.seek(seekPoint);
                    raf.write(str.getBytes());
                    log.info("更换后：{}",str);
                    break;
                }
                lastPoint = ponit;
                lastIsBlank = currentIsBlank;
            }
            flag = true;
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    public static Map<String, Object> getListJsonData(String fileName, Map<String,Object> requestMap){
        if(!isExistFile(fileName)){
            return null;
        }
        int row = 0,count = 0;
        int pageNo = (int)requestMap.get("pageNo");
        int pageSize = (int)requestMap.get("pageSize");
        String searchKey = (String) requestMap.get("searchKey");
        int endRow = pageNo * pageSize;
        int startRow = endRow - pageSize;
        List<JSONObject> dataList = new ArrayList<>(pageSize);
        HashMap<String, Object> map = new HashMap<>(2);
        List<JSONObject> allData = new ArrayList<>(256);
        try {
            LineIterator iterator = FileUtils.lineIterator(new File(fileName), "UTf-8");
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                if(line.contains("{")){
                    String jsondString = line;
                    if(StringUtils.isNotBlank(searchKey)){
                        JSONObject jsonObject = JSON.parseObject(jsondString);
                         String javaBeanName = jsonObject.getString("javaBeanName");
                         String tableName = jsonObject.getString("tableName");
                         if(!javaBeanName.contains(searchKey) && !tableName.contains(searchKey)){
                             //如果有模糊查询，则匹配
                             continue;
                         }
                    }
                    allData.add(JSONObject.parseObject(jsondString));
                    count++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(allData != null && allData.size() > 1){
            // 倒序
            Collections.sort(allData, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    return o1.getLong("createTime") >= o2.getLong("createTime") ? -1 : 1;
                }
            });
        }
        for (JSONObject jsonObject : allData){
            if(row >= startRow && row < endRow){
                dataList.add(jsonObject);
            }
            row++;
        }

        map.put("pageCount", count);
        map.put("dataList", JSON.toJSONString(dataList));
        return map;
    }


    public void apacheCommonsIo(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }

        try {
            LineIterator iterator = FileUtils.lineIterator(file, "UTf-8");
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                // TODO
                // System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Title: removeFileLine
     * @Description: TODO(该方法为从文件开头删除前n行)
     * @param: @param file 文件
     * @param: @param lineNum 删除的行行数
     * @param: @throws IOException
     * @return: void
     * @throws
     */
    public static boolean removeFileLine(File file, int lineNum, String id) {
        RandomAccessFile raf = null;
        boolean flag = false;
        String line = null;
        long writePosition = 0L;
        long readPosition = 0L;
        boolean startFlag = false;
        long lastPosition = 0L;
        int off = 0;
        int len = 0;
        try {
            raf = new RandomAccessFile(file, "rw");
            // Initial write position.
            // 写文件的位置标记,从文件开头开始,后续读取文件内容从该标记开始
            while ((line = raf.readLine()) != null) {
                long position = raf.getFilePointer();
                if(StringUtils.isNotBlank(line) && line.contains(id)){
                    writePosition = position;
                    startFlag = true;
                    continue;
                }
                if(startFlag){
                    readPosition = position;
                    startFlag = false;
                    raf.seek(writePosition);
                    len = (int)(readPosition - lastPosition);
                    off = Integer.valueOf(String.valueOf(lastPosition));
                    break;
                }
                lastPosition = position;
            }
            // Shift the next lines upwards.
            // 读文件的位置标记,写完之后回到该标记继续读该行

            // 利用两个标记,
//            byte[] buff = new byte[1024];
//            int n;
//            while (-1 != (n = raf.read(buff))) {
//                raf.seek(writePosition);
//                raf.write(buff, 0, n);
//                readPosition += n;
//                writePosition += n;
//                raf.seek(readPosition);
//            }
            //raf.setLength(writePosition);
            flag = true;
        } catch (IOException e) {
            log.error("readAndRemoveFirstLines error", e);
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                log.error("close RandomAccessFile error", e);
            }
        }
        removeLineFromFile(file.getPath(), id);
        return flag;
    }

    public static boolean removeLineFromFile(String file, String id) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return false;
            }

            //Construct the new file that will later be renamed to the original filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            //Read from the original file and write to the new
            //unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().contains(id)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            //Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return false;
            }

            //Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return true;
    }


    public static boolean removeRow(String filed, String id){
        File file = new File(filed);
        //将读取出来的数据存入list集合、一个备份、一个正常运行
        //判断文件是否存在、并且有内容
        if(file.exists() && !(file.exists() && file.length() == 0)) {
            log.info("文件存在并且有内容");

            String str = null;
            try {
                ArrayList<String> list = new ArrayList<>();
                //BufferedReader是可以按行读取文件
                FileInputStream inputStream = new FileInputStream(filed);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                while((str = bufferedReader.readLine()) != null)
                {
                    //如果有空格、去掉空格
                    if(str.contains(" ")) {
                        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                        Matcher m = p.matcher(str);
                        str = m.replaceAll("");
                    }
                    //如果不是空串、添加到list、然后提交
                    if(!str.equals("") && StringUtils.isNotBlank(str) && !str.contains(id) ) {
                        System.out.println(str);
                        list.add(str);
                    }
                }
                bufferedReader.close();
                inputStream.close();
                FileOutputStream fileOutputStream = new FileOutputStream(filed);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
                BufferedWriter bw = new BufferedWriter(outputStreamWriter);

                if(list.size() != 0)
                    for (String string : list) {
                        bw.write(string);
                        bw.newLine();
                        System.out.println(string);
                    }
                else if(list.size() == 0) {
                    bw.write("");
                }
                bw.flush();
                bw.close();
                //file.delete();
                return true;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            log.warn("文件不存在、或者文件无内容");
        }

        return false;
    }
}
